﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Peak.Core;
using System.IO;

namespace Peak.ApplicationServices.CsvWritter
{
  public class StoriesCSVWriter
  {
    private const char Separator = ';';

    public void Write(IEnumerable<Story> stories, TextWriter textWriter)
    {
      WriteHeader(textWriter);
      foreach (Story story in stories)
      {
        WriteStory(story, textWriter);
      }
    }

    private void WriteStory(Story story, TextWriter textWriter)
    {
      WriteItem(story.Category, textWriter);
      WriteItem(story.Name, textWriter);
      WriteItem(story.Description, textWriter);
      WriteItem(story.Priority.ToString(), textWriter);
      WriteItem(story.Status.ToString(), textWriter);
      WriteItem(story.HowToDemo, textWriter);
      WriteItem(story.StoryPoints.ToString(), textWriter);
      WriteItem(story.Created.ToString(), textWriter);
      WriteItem(story.CreatedBy, textWriter);
      textWriter.WriteLine();
    }

    private void WriteHeader(TextWriter textWriter)
    {
      WriteItem("Category",textWriter);
      WriteItem("Name", textWriter);
      WriteItem("Description", textWriter);
      WriteItem("Priority", textWriter);
      WriteItem("Status", textWriter);
      WriteItem("HowToDemo", textWriter);
      WriteItem("StoryPoints", textWriter);
      WriteItem("Created", textWriter);
      WriteItem("CreatedBy", textWriter);
      textWriter.WriteLine();
    }

    private void WriteItem(object item, TextWriter textWriter)
    {
      if (item != null)
      {
        string s = item.ToString().Trim();
        if (s.IndexOfAny("\",\x0A\x0D".ToCharArray()) > -1)
          textWriter.Write("\"" + s.Replace("\"", "\"\"") + "\"");
        else
          textWriter.Write(s);
      }
      textWriter.Write(Separator);
    }
  }
}
